﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using CMS.DI;
using CMS.Extend;
using Common.Global;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace CMS
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
              .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //注入HttpContextAccessor
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


            services.Configure<CookiePolicyOptions>(options =>
            {     
                options.CheckConsentNeeded = context => false;//解决Session为空问题
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //添加 Cookie 服务
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
                AddCookie(UserAuthorizeAttribute.UserAuthenticationScheme, options =>
            {
                options.LoginPath = "/Admin/Login/Index";
                options.LogoutPath = "/Admin/Login/OutLogin";
                options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
            }); 
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(15);
                options.Cookie.HttpOnly = true;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddControllersAsServices() //支持属性注入
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new
                    Newtonsoft.Json.Serialization.DefaultContractResolver();//返回前端json字符串大小写原样输出
                    options.SerializerSettings.DateFormatString = "yyyy/MM/dd HH:mm:ss";//解决日期带T的问题
                });

            return services.Configure(this.Configuration);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor accessor)
        {
            //获取全局对象
            Common.Global.HttpContext.Configure(accessor);
            ServiceLocator.Instance = app.ApplicationServices;
          
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseAuthentication();


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute("areas", "{area:exists}/{controller=Login}/{action=Index}/{Id?}");
            });        
        }
    }
}
